package Cain.led 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	/**
	 * 單燈號LED群組
	 * @author Cain
	 */
	public class LED_2Light_Grup extends EventDispatcher
	{
		/**
		 * 順序
		 */
		static public const LOOP:String = "loop";
		/**
		 * 順序一輪
		 */
		static public const LOOP_END:String = "LOOP_END";
		/**
		 * 狂閃
		 */
		static public const FLICKER:String = "Flicker";
		private var led_arr:Array;
		private var num:int;
		private var id:int;
		private var timer:Timer;
		/**
		 * 建構群組
		 * @param	_arr 單燈LED陣列
		 */
		public function LED_2Light_Grup(_arr:Array)
		{
			led_arr = _arr;
			num = led_arr.length;
		}
		/**
		 * 閃燈
		 * @param	_type 顯示形態
		 * @param	_s 燈亮時間序
		 */
		public function play(_type:String = LOOP,_s:Number = .5):void 
		{
			switch (_type) 
			{
				case LOOP:
					loop(_s); //順序燈亮
					break;
				case FLICKER: //狂閃
					Flicker(_s);
					break;
				default:
					throw new Error("燈號顯示type輸入錯誤");
			}
		}
		
		
		/**
		 * 停止
		 */
		public function stop():void 
		{
			if (timer != null) 
			{
				timer.stop();
			}
		}
		/**
		 * 停止後繼續
		 */
		public function go():void 
		{
			timer.start();
		}
		/**
		 * 重置
		 */
		public function reset():void 
		{
			if (timer != null)
			{
				stop();
				timer.reset();
				for each (var _led:LED in led_arr) 
				{
					_led.swich = false;
				}
				id = 0;
				timer = null;
			}
		}
		private function Flicker(_s:Number):void //狂閃
		{
			timer = new Timer(_s * 1000);
			timer.addEventListener(TimerEvent.TIMER, Flicker_onTIMER);
			timer.start();
		}
		
		private function Flicker_onTIMER(e:TimerEvent):void 
		{
			if (led_arr[0].swich) 
			{
				for each (var _led:LED in led_arr) 
				{
					_led.swich = false;
				}
			}else 
			{
				for each (var _led2:LED in led_arr) 
				{
					_led2.swich = true;
				}
			}
		}
		private function loop(_s:Number):void //順序燈亮
		{
			timer = new Timer(_s * 1000, num);
			timer.addEventListener(TimerEvent.TIMER, loop_onTIMER);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, loop_onTIMER_COMPLETE);
			led_arr[id].swich = true;
			timer.start();
		}
		private function loop_next():void 
		{
			led_arr[id].swich = false;
			id++;
			if (id>=num) 
			{
				id = 0;
			}
			led_arr[id].swich = true;
		}
		private function loop_onTIMER_COMPLETE(e:TimerEvent):void 
		{
			timer.removeEventListener(TimerEvent.TIMER, loop_onTIMER);
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, loop_onTIMER_COMPLETE);
			id = 0;
			dispatchEvent(new Event(LOOP_END));
		}
		
		private function loop_onTIMER(e:TimerEvent):void 
		{
			loop_next();
		}
	}

}